<template>
	<view class="u-page" :style="skin">
		<image class="bg" :src="`${assetsPath}/paybg.png`" mode="widthFix"></image>
		<zx-nav color="#fff" title="支付金额" fixedTop></zx-nav>
		<view class="main">
			<view class="card mt20 pricebar">
				<view class="title">需支付金额（元）</view>
				<view class="price">
					<text class="unit">¥</text>
					<text>{{ need_amount || 0 }}</text>
				</view>
			</view>
			<view class="card mt20 paywaybar">
				<u-cell :border="false" @tap="checkPayWay('balance')">
					<view class="title flex align-center balance" slot="title">
						<image src="/static/wallet.png" mode="widthFix"></image>
						<view>
							<view>余额：{{ user_amount || 0.0 }}元</view>
							<view class="tip" v-if="user_amount > 0">当前账户有可用余额，优先使用余额支付</view>
						</view>
					</view>
					<view slot="value" :style="{ opacity: user_amount > 0 ? 1 : 0.3 }"><mycheckbox :state="balance" size="lg"></mycheckbox></view>
				</u-cell>
				<u-cell :border="false" @tap="checkPayWay('tenpay')">
					<view class="title flex align-center tenpay" slot="title">
						<image src="/static/tenPay.png" mode="widthFix"></image>
						<text>微信支付</text>
					</view>
					<view slot="value"><mycheckbox :state="tenpay" size="lg"></mycheckbox></view>
				</u-cell>
			</view>
		</view>
		<view class="btn-success">
			<u-button @click="pay" shape="circle" :loading="btnLoading" type="success" :text="tenpay ? '微信支付¥' + amount : '余额支付'"></u-button>
		</view>
		<view class="behalf" @tap="behalfPay('behalf')">
			<text>找人代付&gt;</text>
		</view>
		<behalfMod ref="behalfMod" @hideModal="hideBehalfMod"></behalfMod>
	</view>
</template>

<script>
import mycheckbox from '@/components/mycheckbox';
import behalfMod from '@/components/behalfMod.vue';
import { mapActions, mapState } from 'vuex';
export default {
	data() {
		return {
			btnLoading: false,
			payway: 'tenpay',
			balance: 0,
			tenpay: 0,
			need_amount: 0,
			user_amount: 0,
			behalf: 0,
			param: {},
			shareOrderNo: ''
		};
	},
	components: { mycheckbox, behalfMod },
	computed: {
		...mapState(['userInfo']),
		amount() {
			return this.tenpay ? (this.balance == 0 ? parseFloat(this.need_amount) : (this.need_amount - this.user_amount).toFixed(2)) : 0.0;
		}
	},
	onLoad(options) {
		let { need_amount, user_amount, order_id, order_no, ...param } = options;
		this.need_amount = need_amount;
		this.param = { ...param };
		this.order_no = order_no || '';
		this.order_id = order_id || '';
		this.user_amount = user_amount - 0;
		this.balance = this.user_amount > 0 ? 1 : 0;
		this.tenpay = this.user_amount < need_amount ? 1 : 0;
	},
	onShareAppMessage(res) {
		let shareUrl = '/apppay/behalf/behalf';
		shareUrl += '?userId=' + this.userInfo.id + '&orderNo=' + this.shareOrderNo + '&type=1';
		let shareName = '来自' + this.userInfo.wx_name + '的代付';
		return {
			title: shareName,
			path: shareUrl,
			imageUrl: ''
		};
	},
	methods: {
		...mapActions(['getCarCount']),
		checkPayWay(payway) {
			this.behalf = 0; //把代付的状态置空
			if (payway == 'balance' && this.user_amount > 0) {
				this.balance = this.balance == 1 ? 0 : 1;
				if (this.balance && this.user_amount >= this.need_amount) {
					this.tenpay = 0;
				}
			} else if (payway == 'tenpay') {
				this.tenpay = this.tenpay == 1 ? 0 : 1;
				if (this.tenpay && this.user_amount >= this.need_amount) {
					this.balance = 0;
				}
			}
		},
		pay() {
			if (this.tenpay == 0) {
				if (this.balance == 0 && this.alipay == 0) {
					uni.showToast({
						title: '请至少选择一种支付方式',
						icon: 'none'
					});
					return;
				} else if (this.balance == 1 && this.alipay == 0 && this.user_amount < this.need_amount) {
					uni.showToast({
						title: '当前账户余额不足，请使用组合支付或者微信支付',
						icon: 'none'
					});
					return;
				}
			}
			if (this.order_id) {
				this.orderConfirmPay(this.order_id);
			} else {
				this.submitOrder(this.param);
			}
		},
		//提交订单
		submitOrder(param) {
			/* 如果正在支付 */
			if (this.btnLoading) {
				return;
			}
			this.btnLoading = true;
			console.log('param', param);
			uni.login({
				provider: 'weixin',
				success: loginRes => {
					this.$postAction(
						this.$api.submitOrder,
						{
							...param,
							is_balance: this.behalf == 1 ? 0 : this.balance,
							code: loginRes.code
						},
						{
							custom: {
								catch: true
							}
						}
					)
						.then(res => {
							if (res.code == 0) {
								// this.payOrder(da.data.pay_info);
								const order_no = res.data.order_no;
								//走代付流程
								if (this.behalf == 1) {
									//走代付流程
									this.$refs.behalfMod.show(this.userInfo.id, order_no);
									this.shareOrderNo = order_no;
									this.behalf = 0; //把代付的状态置空
								} else if (res.data.pay_info) {
									const orderInfo = res.data.pay_info;
									this.payOrder(orderInfo, order_no);
								} else {
									uni.showToast({
										icon: 'none',
										title: '订单支付成功'
									});
									setTimeout(function () {
										uni.redirectTo({
											url: '/pages/orderpay/paystate?state=1'
										});
									}, 100);
								}
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								});
							}
						})
						.finally(() => {
							this.btnLoading = false;
							setTimeout(() => {
								this.SetCarTotal();
							}, 800);
						});
				},
				fail: () => {
					this.btnLoading = false;
				}
			});
		},
		//订单支付
		orderConfirmPay(id) {
			let $me = this;
			uni.login({
				provider: 'weixin',
				success: loginRes => {
					$me.$postAction($me.$api.orderPay + '2/' + id, {
						pay_type: 'wx_lite',
						code: loginRes.code,
						is_balance: this.behalf == 1 ? 0 : this.balance
					}).then(da => {
						console.log('确认支付' + JSON.stringify(da));
						if (da.code == 0) {
							let orderInfo = da.data;
							if (this.behalf == 1) {
								//走代付流程
								this.$refs.behalfMod.show(this.userInfo.id, this.order_no, 1);
								this.shareOrderNo = this.order_no;
								this.behalf = 0; //把代付的状态置空
							} else if (orderInfo) {
								this.payOrder(orderInfo, this.order_no);
							} else {
								uni.showToast({
									icon: 'none',
									title: '订单支付成功'
								});
								setTimeout(function () {
									uni.redirectTo({
										url: '/pages/orderpay/paystate?state=1'
									});
								}, 100);
							}
						}
					});
				}
			});
		},
		//订单支付
		payOrder(orderInfo) {
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: orderInfo.timeStamp,
				nonceStr: orderInfo.nonceStr,
				package: orderInfo.package,
				signType: orderInfo.signType,
				paySign: orderInfo.paySign,
				service: 3,
				success: function (res) {
					setTimeout(function () {
						uni.redirectTo({
							url: '/pages/orderpay/paystate?state=1'
						});
					}, 100);
				},

				fail: function (err) {
					console.log('err', err);
					// uni.showToast({
					// 	icon: 'none',
					// 	title: '订单支付失败'
					// });
					setTimeout(function () {
						uni.redirectTo({
							url: '/pages/orderpay/paystate?state=0'
						});
					}, 100);
				}
			});
		},
		behalfPay() {
			this.behalf = 1;
			if (this.order_id) {
				this.orderConfirmPay(this.order_id);
			} else {
				this.submitOrder(this.param);
			}
		},
		/* 关闭代付弹出，需要返回到订单列表页面 */
		hideBehalfMod() {
			console.log('触发了吗');
			setTimeout(function () {
				if (this.order_id) {
					/* 返回上一页 */
					uni.navigateBack();
				} else {
					/* 跳转列表页面 */
					uni.redirectTo({
						url: '/pages/orderlist/orderlist?tabindex=' + 0
					});
				}
			}, 100);
		}
	}
};
</script>

<style lang="scss">
.bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
}
.main {
	position: relative;
	z-index: 1;
}
.card {
	&.paywaybar {
		padding: 40rpx 0;
	}
	.title {
		color: #1c1c1e;
		font-weight: 500;
		font-size: 32upx;
	}
	.tip {
		font-size: 24rpx;
		font-weight: 400;
		color: var(--nav-bg);
	}
	::v-deep .u-cell + .u-cell {
		margin-top: 20rpx;
	}
}
.tenpay {
	image {
		height: 62upx;
		width: 70upx;
		display: block;
		margin-right: 25upx;
	}
}
.balance {
	image {
		height: 72upx;
		width: 72upx;
		display: block;
		margin-right: 24upx;
	}
}
.pricebar {
	text-align: center;
	padding: 40rpx 0;
	.title {
		color: #848484;
		font-size: 28upx;
	}
	.price {
		vertical-align: bottom;
		font-size: 68upx;
		font-weight: 500;
		color: #2c2c2e;
		padding: 15upx 0;
		.unit {
			font-size: 36upx;
			margin-right: 8upx;
		}
	}
}
.btn-success {
	margin: 60upx 28rpx 0;
	::v-deep .u-button--success {
		height: 88rpx !important;
		box-shadow: 0px 12rpx 24rpx -9rpx #ffbec2;
	}
}
.behalf {
	text-align: right;
	color: var(--nav-bg);
	margin-top: 28upx;
	margin-right: 30upx;

	text {
		text-decoration: underline;
	}
}
</style>
